<?php

namespace App\Http\Services;

use App\Http\Model\FinanceDiamond;
use App\Http\Model\FinanceRoomWealth;
use App\Http\Model\FinanceUserWallet;
use App\Http\Model\FinanceUserWallet as FinanceUserWalletModel;
use App\Http\Model\Hint;
use App\Http\Model\Prop;
use App\Http\Model\PropEvent;
use App\Http\Model\PropLog;
use App\Http\Model\PropUserPack;
use App\Http\Model\Room;
use App\Http\Model\Union;
use App\Http\Model\UnionRank;
use App\Http\Model\UnionUser;
use App\Http\Model\User;
use App\Http\Model\UnionParam;
use Illuminate\Support\Facades\DB;

class UnionRankServices extends CommonServices
{
    protected $model_union_rank;
    protected $finance_room_wealth;
    protected $model_union;
    protected $model_user;
    protected $model_finance_wallet;
    protected $model_diamond;
    protected $model_union_user;
    protected $model_prop_event;
    protected $model_prop_log;
    protected $model_prop_user_pack;
    protected $model_prop;
    protected $model_room;
    protected $model_finance_room_wealth;
    protected $model_union_param;
    public function __construct()
    {
        $this->model_union_rank = new UnionRank();
        $this->model_union = new Union();
        $this->model_user = new User();
        $this->finance_room_wealth = new FinanceRoomWealth();
        $this->model_finance_wallet = new FinanceUserWalletModel();
        $this->model_diamond = new FinanceDiamond();
        $this->model_union_user = new UnionUser();
        $this->model_prop_event = new PropEvent();
        $this->model_prop_log = new PropLog();
        $this->model_prop_user_pack = new PropUserPack();
        $this->model_prop = new Prop();
        $this->model_room = new Room();
        $this->model_finance_room_wealth = new FinanceRoomWealth();
        $this->model_union_param = new UnionParam();
    }

    /**获取等级列表
     * @return array
     */
    public function getRankList(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        do {
            $this->I('type', '分类', 'int', false); //-1 全部 1：财富等级 2：活跃等级
            $type = $this->requestData['type'] ?? -1;
            $data = $this->model_union_rank->getRankList($type);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**设置活跃等级
     * @return array
     */
    public function setActiveWealth(){
        return $this->model_union_rank->setActiveWealth();
    }

    /**设置财富等级
     * @return array
     */
    public function setWealth($union_id = 0){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        if(!empty($union_id)){
            $union_temp = $this->model_union->getUnionInfo($union_id);
            $unions[] = $union_temp;
        }else{
            $unions = $this->model_union->getAllUnion();
        }
        //五种特权
        $union_privilege = $this->model_union_rank->getPrivilege();
        //有特权的公会
        $union_users_privilege = $this->model_union_param->getParams(array_column($unions,'id'));
        $union_users_privilege = !empty($union_users_privilege) ? array_column($union_users_privilege,null,'union_id') : [];
        $data_wealth = array();
        $data_wealth_level = array();
        $data_message = array();
        foreach ($unions as $union){
            $room_list= $this->getUnionRoomList($union['id']);
            $room_ids = array_column($room_list, 'room_id');
            $union_wealth = $this->model_finance_room_wealth->getAllWealthTotalToRoomIds($room_ids);
            $total = empty($union_wealth['total'] / 100) ? 0 : intval($union_wealth['total'] / 100);
            $supply_total = $this->model_union->supplyUnionTotal($union_id);
            $total = $total+$supply_total;
            //todo 设置财富值
            if ($total > 80000000) {
                $level = 15;
            } else {
                $union_rank = $this->model_union->getUnionRank($total);
                $level = $union_rank[0]['level'];
            }
            $data_wealth[$union['id']] = $total;
            $data_wealth_level[$union['id']] = $level;
            $data_p = array();
            $privilege_name = '';
            if($union['deposit'] >= $union_privilege[0]['start_value'] && $level >= $union_privilege[0]['level']){
                $data_p['a_daily_advance'] = 1;
                $privilege_name = $union_privilege[0]['name'];
            }else{
                $data_p['a_daily_advance'] = 0;
            }
            if($union['deposit'] >= $union_privilege[1]['start_value'] && $level >= $union_privilege[1]['level']){
                $data_p['a_self_advance'] = 1;
                $privilege_name = $union_privilege[1]['name'];
            }else{
                $data_p['a_self_advance'] = 0;
            }
            if($union['deposit'] >= $union_privilege[2]['start_value'] && $level >= $union_privilege[2]['level']){
                $data_p['a_set_advance'] = 1;
                $privilege_name = $union_privilege[2]['name'];
            }else{
                $data_p['a_set_advance'] = 0;
            }
            if($union['deposit'] >= $union_privilege[3]['start_value'] && $level >= $union_privilege[3]['level']){
                $data_p['a_daily_withdraw'] = 1;
                $privilege_name = $union_privilege[3]['name'];
            }else{
                $data_p['a_daily_withdraw'] = 0;
            }
            if($union['deposit'] >= $union_privilege[4]['start_value'] && $level >= $union_privilege[4]['level']){
                $data_p['a_set_withdraw'] = 1;
                $privilege_name = $union_privilege[4]['name'];
            }else{
                $data_p['a_set_withdraw'] = 0;
            }
            $union_user_privilege = !empty($union_users_privilege) ? $union_users_privilege[$union['id']] : [];
            //todo 判断特权是否需要变更
            $update_privilege = array();
            foreach ($data_p as $k=>$v){
                if(empty($union_user_privilege) && $v>0){
                    $update_privilege[$k] = 1;
                    $insert = 1;
                    $data_message[$union['id']]['privilege_name'] = $privilege_name;
                    $data_message[$union['id']]['user_id'] = $union['un_user_id'];
                }else if(!empty($union_user_privilege) && $union_user_privilege[$k] != $v){
                    $update_privilege[$k] = $v;
                    $insert = 0;
                    if($v==1){
                        $data_message[$union['id']]['privilege_name'] = $privilege_name;
                        $data_message[$union['id']]['user_id'] = $union['un_user_id'];
                    }
                }
            }

            if(!empty($update_privilege)){
                if($insert ==1){
                    $update_privilege['union_id'] = $union['id'];
                    $this->model_union_param->createAutomaticParam($update_privilege);
                }else{
                    $this->model_union_param->updateAutomaticParam($union['id'],$update_privilege);
                }
            }
        }
        if(!empty($data_wealth)){
            $this->model_union_rank->setWealth($data_wealth);
            $this->model_union_rank->setWealthLevel($data_wealth_level);
        }
        $data = $data_message;
        return compact('code', 'msg', 'data');

    }

    /**获取公会认证信息
     * @return array
     */
    public function getQualificationInfo(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        do {
            $this->I('union_id', '公会id', 'int', true);
            $this->I('user_id', '会长id', 'int', true);

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化
            $data = $this->model_union->getUnionInfo($this->requestData['union_id']);
            if(!empty($data)){
                $wallet = $this->model_finance_wallet->get_wallet($data['un_user_id']);
                $data['diamond'] = isset($wallet['diamond_balance']) ? $wallet['diamond_balance'] : 0;
                $data['portrait'] = build_image($data['portrait']);
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**统计每日消费，更新贡献值
     * @return array
     */
    public function updateContributionByConsume(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $user_ids = $this->model_union_rank->getTodayConsumeFinishUser();
        $res = $this->model_diamond->statisticsEveryDayDiamondByUid($user_ids);
        $consume_arr = [];
        foreach ($res as $d){
            if(empty($consume_arr[$d['user_id']])){
                $consume_arr[$d['user_id']] = $d['diamond_value'];
            }
        }
        $data = [];
        $finish_user = array();
        foreach ($consume_arr as $k=>$v){
            if($v<-500){
                $finish_user[$k] = $v;
            }
        }
        $user_union = $this->model_union_user->getUnionByUser(array_keys($finish_user));
        $redis_finish_user = array();
        foreach ($user_union as $u){
            $data[] = $u['user_id'];
            $this->model_union_rank->incUserContribution($u['un_id'] ,$u['user_id'] ,20);
            $this->model_union_rank->addContributionLog($u['un_id'] ,$u['user_id'] ,20 ,3,'消费');
            $redis_finish_user[$u['user_id']] = 20;
        }
        if(!empty($redis_finish_user)){
            $this->model_union_rank->setTodayConsumeFinishUser($redis_finish_user);
        }
        $data = $redis_finish_user;
        return compact('code', 'msg', 'data');
    }

    /**礼包列表
     * @return array
     */
    public function getBagList(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = array();
        $res = $this->model_union_rank->getBagList();
        $receive_logs = $this->model_union_rank->getReceiveBagLog($this->requestData['user_id']);
        $receive_log_id = !empty($receive_logs) ? array_column($receive_logs ,'id' ,'bag_id') : [];
        foreach ($res as &$r){
            $r['receive_status'] = !empty($receive_log_id[$r['id']]) ? 1 : 0;
            $data[] = $r;
        }
        return compact('code', 'msg', 'data');
    }

    /**领取礼包
     * @return array
     */
    public function bagReceive(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $this->I('bag_id', 'bag_id', 'int', true);
            $this->I('union_id', 'union_id', 'int', true);
            $this->I('user_id', 'user_id', 'int', true);
            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            $union_user = $this->model_union_user->userRole($this->requestData['user_id'] ,$this->requestData['union_id']);
            if(empty($union_user)){
                $code = Hint::ERR_DATA_NOT_EXIST;
                $msg = '不在当前公会，不能领取礼包';
                break;
            }
            $bag = $this->model_union_rank->getBagById($this->requestData['bag_id']);
            if(empty($bag)){
                $code = Hint::ERR_DATA_NOT_EXIST;
                $msg = '礼包' . Hint::getErrCodeMsg($code);
                break;
            }
            //判断财富等级
            $level = $this->model_union_rank->getWealthLevel($this->requestData['union_id']);
            if($level < $bag['level']){
                $code = Hint::UNION_FINANCE_RANK_NOT_ENOUGH;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
            // 查询道具
            $getPropEventList = $this->model_prop_event->getPropEventByPropId($bag['prop_id']);
            if (empty($getPropEventList)) {
                $code = Hint::ERR_DATA_NOT_EXIST;
                $msg = '道具' . Hint::getErrCodeMsg($code);
                break;
            }
            //判断当前礼包是否领取过 todo
            $receive_log = $this->model_union_rank->getReceiveBagLog($this->requestData['user_id'] ,$bag['id']);
            if($receive_log){
                $code = Hint::UNION_BAG_RECEIVED;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
            DB::beginTransaction();
            // 创建发放日志
            $propLogData = [
                "user_id" => $this->requestData['user_id'],
                "prop_id" => $bag['prop_id'],
                "suid" => 0,
                "type" => 24,
                "change" => 1
            ];
            $updateOrInsertPropLog = $this->model_prop_log->updateOrInsertPropLog($propLogData);
            if (!$updateOrInsertPropLog) {
                DB::rollBack();
                $code = Hint::ERR_DATA_CREATE_FAIL;
                $msg = '道具发放日志' . Hint::getErrCodeMsg($code);
                break;
            }

            //放入用户背包 TODO 自动发送
            $params = [
                'user_id' => $this->requestData['user_id'],
                'prop_id' => $bag['prop_id'],
                'num' => 1,
            ];

            // 检测用户背包道具是否存在
            $inputType = 'insert';
            $checkUserPack = $this->model_prop_user_pack->checkUserPack($this->requestData['user_id'], $bag['prop_id']);
            if (!empty($checkUserPack)) {
                $inputType = 'increment';
                $params['user_pack_id'] = $checkUserPack['user_pack_id'];
            }
            // 创建/更新 用户背包
            $ret = $this->model_prop_user_pack->updateOrInsertUserPack($params, $inputType);
            if (!$ret) {
                $code = Hint::ERR_DATA_UPDATE_FAIL;
                $msg = '用户背包' . Hint::getErrCodeMsg($code);
                break;
            }
            $this->model_union_rank->addBagReceiveLog($this->requestData['union_id'] ,$this->requestData['user_id'] ,$bag['id'] , $bag['prop_id'],$bag['level']);
            DB::commit();
        } while (false);

        return compact('code', 'msg', 'data');
    }

    //获取公会房间列表
    public function getUnionRoomList($union_id)
    {
        $union_rooms_ids = $this->model_union->getUnionRoomIds($union_id);
        $room_ids = [];
        if ($union_rooms_ids) {
            $room_ids = array_column($union_rooms_ids, 'room_id');
        }
        $union_room_list = $this->model_room->get_rooms_by_ids($room_ids);
        $un_room_open = [];
        $un_room_close = [];
        foreach ($union_room_list as $key => $value) {
            //房间是否开启
            $opened = $this->model_room->get_opened($value['room_id']);
            if ($opened) {
                $value['opened'] = true;
                $un_room_open[] = $value;
            } else {
                $value['opened'] = false;
                $un_room_close[] = $value;
            }
        }

        if ($un_room_open) {
            return array_merge($un_room_open, $un_room_close);
        }
        return $un_room_close;
    }

    /**获取公会特权
     * @return array
     */
    public function getPresidentPrivilege(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $this->I('union_id', 'union_id', 'int', true);
            $this->I('user_id', 'user_id', 'int', true);

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            $union_info = $this->model_union_user->userToUnion($this->requestData['user_id'] ,3);
            if($union_info['un_user_id'] != $this->requestData['user_id']){
                $code = Hint::AUTH_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
            $deposit = $union_info['deposit'] ?? 0;
            $union_privilege = $this->model_union_rank->getPrivilege();
            $level = $this->model_union_rank->getWealthLevel($this->requestData['union_id']);
            $user_privilege = $this->model_union_param->getParams($this->requestData['union_id']);
            $user_to_privilege = array(
                !empty($user_privilege['m_daily_advance']) ? $user_privilege['m_daily_advance'] : 0,
                !empty($user_privilege['m_self_advance']) ? $user_privilege['m_self_advance'] : 0,
                !empty($user_privilege['m_set_advance']) ? $user_privilege['m_set_advance'] : 0,
                !empty($user_privilege['m_daily_withdraw']) ? $user_privilege['m_daily_withdraw'] : 0,
                !empty($user_privilege['m_set_withdraw']) ? $user_privilege['m_set_withdraw'] : 0,
            );
            $advance = array();
            $withdraw = array();
            foreach ($union_privilege as $k=>&$val){
                if($deposit >= $val['start_value']){
                    $val['auth_status'] = 1;
                }else{
                    $val['auth_status'] = 0;
                }
                if($level>=$val['level']){
                    $val['wealth_status'] = 1;
                }else{
                    $val['wealth_status'] = 0;
                }
                if($user_to_privilege[$k] ==1 || ($deposit >= $val['start_value'] && $level>=$val['level'])){
                    $val['status'] = 1;
                }else{
                    $val['status'] = 0;
                }
                if($val['type'] == 1){
                    $advance[] = $val;
                }else{
                    $withdraw[] = $val;
                }
            }
            $data['advance'] = $advance;
            $data['withdraw'] = $withdraw;
            $data['today_is_advance_date'] = false;
        } while (false);

        return compact('code', 'msg', 'data');
    }

    public function setTodayUnionInfoToRedis(){
        $this->model_union_rank->setTodayUnionInfoToRedis();
    }
}


